<template>
    <div class="dashboard" @mousemove="mousemove" v-loading.fullscreen.lock="fullscreenLoading" element-loading-text="加载中" element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)">
        <div class="dashboard-header">
            <!-- <h1>{{TitleReservoir02}}堤坝安全运行监测平台</h1>  -->
            <!-- 省市县一体化堤坝安全运行监测平台大数据中心 -->
            <h1 style="font-size:30px">省市县一体化水库堤坝安全运行监测大数据可视化平台</h1> 
            
        </div>
        <div class="dashboard-box">
            <div class="dashboard-left">
                <div class="neirong-top">
                    <equipment v-if="equipmentData" :data="equipmentData" @onState="onwState"/>
                </div>
                <div class="neirong-middle">
                    <riskLevel v-if="riskLevelData" :data="riskLevelData" @onRiskeve="getRiskLevelData"/>
                </div>
                <div class="neirong-bottom">
                    <middle02 v-if="siteReservoirData" :data="siteReservoirData"/>
                </div>
            </div>
            <div class="dashboard-right">
                <div class="neirong-top">
                    <middle06 v-if="siteReservoirData" :data="siteReservoirData"/>
                </div>
                <div class="neirong-middle">
                    <middle05 v-if="siteReservoirData" :data="siteReservoirData"/>
                </div>
                <div class="neirong-bottom">
                    <middle08 :data="StationVideo"/>
                </div>
            </div>
        </div>
        <div class="input-Calendar">
            <el-input
                v-model="searchReservoir"
                placeholder="请输入搜索名称"
                :prefix-icon="'el-icon-search'"
                @change="onSearchReservoir"
            />
        </div>
        <div class="text-switch">
            <el-switch
            v-model="switchValue"
            @change="onSwitchVal"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#002D4C"/>
            <div class="text-name">水库名</div>
        </div>
        <div id="container" class="maptongy"></div>
    </div>
</template>

<script>
import equipment from './equipment.vue'
import middle02 from './middle02.vue'
import middle05 from './middle05.vue'
import middle06 from './middle06.vue'
import middle08 from './middle08.vue'
import riskLevel from './riskLevel.vue'
import { Url } from '@/api/url'
import { formatTimestamp } from '@/utils/common'
import AMapLoader from '@amap/amap-jsapi-loader';
import homeApi from '@/api/home'
import dashboardsApi from '@/api/dashboard'
let map,cluster,markerdd
export default {
    name: 'dashboard',
    components: {
        equipment,
        middle02,
        middle05,
        middle06,
        middle08,
        riskLevel,
    },
    data() {
        return {
            Url,
            TitleReservoir:'水库',
            TitleReservoir02:'水库',
            fullscreenLoading:false,
            equipmentData: null,
            riskLevelData: null,
            switchValue:1,
            siteReservoirData:null,
            searchReservoir:'',
            nowTime: '',
            Ttime:null,
            timer: null,
            StationVideo:null,
            //搜索延时器
            searchTime:null,
            nowTimer: null,
            AMap:null,
            amampData:null,
        }
    },
    created() {
        this.getData()
    },
    unmounted() {
    },
    methods: {
        //切换站名
        onSwitchVal(val){
            this.amapData(this.amampData)
        },
        //搜索关键字
        onSearchReservoir(val){
            if(val == 0){
                this.getamapData()
            }else {
                dashboardsApi.findByNameList(val).then(res => {
                    this.amapData(res.data)
                }).catch(err=>{
                    this.$message.error(err.message||'操作失败')
                })
            }
        },
        //状态查询地图信息
        onwState(val){
            console.log(val)
            if(val == 0){
                this.getamapData()
            }else {
                dashboardsApi.findByEqList(val).then(res => {
                    this.amapData(res.data)
                }).catch(err=>{
                    this.$message.error(err.message||'操作失败')
                })
            }
        },
        //风险等级查询地图信息
        getRiskLevelData(val){
            dashboardsApi.findRiskList(val).then(res => {
                    this.amapData(res.data)
                }).catch(err=>{
                    this.$message.error(err.message||'操作失败')
                })
        },
        //根据设备编码查询设备信息 
        getEquipmentCodeData(val){
            this.getvideo('01',val)
            dashboardsApi.findByIdEq({stationId:val.stationId?val.stationId:val.station_id}).then(res => {
                    this.getGeologyImge(res.data)
                }).catch(err=>{
                    this.$message.error(err.message||'操作失败')
                })
        },
        //获取视频地址
        getvideo(val,item){
            dashboardsApi.getvideo({
                cameraCode:val,
                stationId:item.stationId
            }).then(res => {
                this.StationVideo = res.data
            }).catch(err=>{
                this.$message.error(err.message||'操作失败')
            })
        },
        //地质图片
        getGeologyImge(ress){
            let dqData = ress
            if(dqData.geologyEntityList.length > 0){
                homeApi.getGeologyImge({
                    ddatetime:formatTimestamp(new Date()),
                    sensorCode:dqData.geologyEntityList[0].sensorCode,
                    stationId:dqData.stationId
                }).then(res => {
                    dqData.getGeologysImge = res.data
                    this.tanchuandaka(dqData)
                }).catch(err=>{
                    this.tanchuandaka(dqData)
                })
            }else {
                this.tanchuandaka(dqData)
            }
            
        },
        getData() {
            let that = this;
            that.fullscreenLoading = true
            let userInfooo = JSON.parse(localStorage.getItem('userInfo'))
            that.TitleReservoir02 = userInfooo.areaName
            AMapLoader.load({
                key: "fbb296dc6c8c05c7437fa620659f5e9f", // 申请好的Web端开发者Key
                version: "2.0",
                // AMapUI: {
                //     version: '1.1',   // AMapUI 版本
                //     plugins:['overlay/SimpleMarker','geo/DistrictExplorer'],       // 需要加载的 AMapUI ui插件
                // },
                plugins : ["AMap.Geocoder","AMap.MarkerClusterer"],
            })
                .then((AMap) => {
                    that.AMap = AMap
                    map = new that.AMap.Map("container", {
                        zoom: 7.6,
                        pitch: 50,
                        skyColor:[0,0,0,0],
                        mapStyle:"amap://styles/7e2c421006ebcf76fb30959e9c6d8da2",
                        viewMode: "3D", // 地图模式
                    });
                    that.fullscreenLoading = false
                    that.getamapData()
                    that.initScreenShow()
                })
                .catch((e) => {
                    console.log(e);
                });
        },
        //地图全部设备
        getamapData(){
            dashboardsApi.findByAllStations().then(res => {
                this.amapData(res.data)
            }).catch(err=>{
                this.$message.error(err.message||'操作失败')
            })
        },
        initScreenShow(){
            dashboardsApi.findByEquit().then(res => {
                this.equipmentData = res.data
            }).catch(err=>{
                this.$message.error(err.message||'操作失败')
            })
            dashboardsApi.findByRisk().then(res => {
                this.riskLevelData = res.data
            }).catch(err=>{
                this.$message.error(err.message||'操作失败')
            })
        },
        amapData(res){
            let that = this
            map.clearMap();
            if(cluster != undefined){
                cluster.setMap(null);
            }
            that.amampData = res
            if(res.length > 0){
                that.reservoirName = res[0].reservoirName ? res[0].reservoirName : res[0].reservoir_name
                // map.setZoomAndCenter(18, [112.93133,28.2351]);
                map.setZoomAndCenter(6, [res[0].lon , res[0].lat]);
                that.getEquipmentCodeData(res[0])
                let markers = [];
                for (var i = 0; i < res.length; i++) {
                    // 创建点实例
                    let marker = {}
                    let lnglat = [res[i].lon, res[i].lat]
                    marker.lnglat = lnglat
                    marker.data = res[i]
                    marker.icon = require('../../assets/img/dashboard/水库.png')
                    // marker.icon = that.nengliaopanduan(res.data[i].alarmStatus,res.data[i].onlineStatus),
                    markers.push(marker);
                }
                let count = markers.length;
                let _renderClusterMarker = function (context) {
                    let factor = Math.pow(context.count / count, 1 / 18);
                    let div = document.createElement('div');
                    let Hue = 180 - factor * 180;
                    let bgColor = 'hsla(' + Hue + ',100%,40%,0.7)';
                    let fontColor = 'hsla(' + Hue + ',100%,90%,1)';
                    let borderColor = 'hsla(' + Hue + ',100%,40%,1)';
                    let shadowColor = 'hsla(' + Hue + ',100%,90%,1)';
                    div.style.backgroundColor = bgColor;
                    let size = Math.round(30 + Math.pow(context.count / count, 1 / 5) * 20);
                    div.style.width = div.style.height = size + 'px';
                    div.style.border = 'solid 1px ' + borderColor;
                    div.style.borderRadius = size / 2 + 'px';
                    div.style.boxShadow = '0 0 5px ' + shadowColor;
                    div.innerHTML = context.count;
                    div.style.lineHeight = size + 'px';
                    div.style.color = fontColor;
                    div.style.fontSize = '14px';
                    div.style.textAlign = 'center';
                    context.marker.setOffset(new that.AMap.Pixel(-size / 2, -size / 2));
                    context.marker.setContent(div)
                };
                    let _renderMarker = function(context) {
                    let content = `<div class="amap-markerYs">
                        <div><img src="${require('../../assets/img/dashboard/水库缩小.png')}"/></div>
                        <div class="markerYs-text" style="width:${context.data[0].data.reservoirName?context.data[0].data.reservoirName.length*20:context.data[0].data.reservoir_name.length*20}px">${context.data[0].data.reservoirName?context.data[0].data.reservoirName:context.data[0].data.reservoir_name}</div>
                    </div>`;
                    // let offset = new _this.AMap.Pixel(-9, -9);
                    that.switchValue == 1 ? context.marker.setContent(content) : context.marker.setIcon(context.data[0].icon)
                    // context.marker.setOffset(offset)
                    context.marker.setPosition(context.data[0].lnglat)
                    // context.marker.setIcon(context.data[0].icon)
                }
                cluster = new that.AMap.MarkerCluster(map, markers, {
                    gridSize: 60,
                    renderClusterMarker: _renderClusterMarker,
                    renderMarker: _renderMarker,
                });
                cluster.on("click", (e) =>{
                    let curZoom = map.getZoom();
                    // map.setZoom(18.5)
                    // map.setCenter([e.clusterData[0].lnglat.lng , e.clusterData[0].lnglat.lat]); 
                    if(e.clusterData.length == 1){
                        curZoom = 18
                        that.getEquipmentCodeData(e.clusterData[0].data)
                    }else {
                        if(curZoom < 20){
                            curZoom += 1;
                        }
                    }
                    map.setZoomAndCenter(curZoom, e.lnglat);
                })
            }
        },
        tanchuandaka(val){
            let that = this
            if(markerdd != undefined){
                    markerdd.setMap(null);
            }
            let zhandianList = ``
            // if(val.geologyEntity){
            //     let zhannameList = ``
            //     let zhanvalList = ``
            //     for (let key in val.geologyEntity) {
            //         if(key.indexOf('freq') == 0){
            //             zhannameList += `<div class="title ellip" style="width:60px" >点位${key.replace(/freq/g,"")}</div>`
            //             zhanvalList += `<div style="width:60px" class="item-name text-overflow item">${val.geologyEntity[key]?val.geologyEntity[key]:'--'}</div>`
            //         }
            //     }
            //     zhandianList = `<div class="duty-bottom">
            //                 <div class="title-left">监测结果</div>
            //                 <div class="list-right">
            //                     <div class="title-list">
            //                     ${zhannameList}
            //                     </div>
            //                     <div class="list-container">
            //                     ${zhanvalList}
            //                     </div>
            //                 </div>
            //             </div>`
            // }
            // 
            zhandianList = `<div class="duty-bottom">
                <img src="data:image/jpg;base64,${val.getGeologysImge}" alt="">
            </div>`
            let content = `<div class="amap-box">
        <div class="title-h">
            <div>
                <img src="${require('@/assets/img/dashboard/装饰_.png')}" alt="">
                实况信息(${val.reservoirName})
            </div>
            <img onclick="onguanbi()" src="${require('@/assets/img/dashboard/边角x.png')}" alt="">
        </div>
        <div class="duty-box">
            <div class="duty-top">
                <div class="shuju-list">
                    <div class="title-list">
                        <div class="title01">
                            ${val.z?val.z:'--'} m
                        </div>
                        <div class="img">
                            <img src="${require('@/assets/img/dashboard/水位.png')}" alt="">
                        </div>
                        <div class="title02">
                            水位
                        </div>
                    </div>
                </div>
                <div class="shuju-list">
                    <div class="title-list">
                        <div class="title01">
                            ${val.r?val.r:'--'} mm
                        </div>
                        <div class="img">
                            <img src="${require('@/assets/img/dashboard/降水.png')}" alt="">
                        </div>
                        <div class="title02">
                            降水
                        </div>
                    </div>
                </div>
                <div class="shuju-list">
                    <div class="title-list">
                        <div class="title01">
                            ${val.fx?val.fx:'--'} ${val.fxGrade?val.fxGrade:'--'}
                        </div>
                        <div class="img">
                            <img src="${require('@/assets/img/dashboard/风力风向.png')}" alt="">
                        </div>
                        <div class="title02">
                            风力风向
                        </div>
                    </div>
                </div>
                <div class="shuju-list">
                    <div class="title-list">
                        <div class="title01">
                            ${val.temp?val.temp:'--'} ℃
                        </div>
                        <div class="img">
                            <img src="${require('@/assets/img/dashboard/温度.png')}" alt="">
                        </div>
                        <div class="title02">
                            温度
                        </div>
                    </div>
                </div>
            </div>
            ${zhandianList}
        </div>
    </div>`
            that.TitleReservoir = val.reservoirName
            that.siteReservoirData = val
            map.setZoomAndCenter(16, [val.lon + 0.005, val.lat]);
            markerdd = new that.AMap.Marker({
                data:val,
                zIndex:50,
                position: new that.AMap.LngLat(val.lon, val.lat),
                content: content, //设置文本标注内容
                // 以 icon 的 [center bottom] 为原点
                offset: new that.AMap.Pixel(that.switchValue == 1 ? val.reservoirName.length * 20 : 50, -200),
                extData : {
                    "data":val,
                }
            });
            // markerdd.off()
            // markerdd.on('click', function (e) {
            //     console.log(e)
            //     // console.log(document.getElementById('imgonclick'))
            //     // _this.amapClick(e.target.getExtData())
            //     // document.getElementById('imgonclick').onclick(this.onguanbi)
            // });
            map.add(markerdd);
        },
        //判断回调
        // nengliaopanduan(zhengchang,zaixian){
        //     let yanse = require('../../assets/img/dapin/map_lixian.png')
        //     if(zaixian == 0){
        //         if(zhengchang == 2){
        //             yanse = require('../../assets/img/dapin/map_chaobiao.png')
        //         }else{
        //             yanse = require('../../assets/img/dapin/map_dabiao.png')
        //         }
        //     }else if(zaixian == 1){
        //         yanse = require('../../assets/img/dapin/map_lixian.png')
        //     }
        //     return yanse
        // },
        mousemove(){
            let that = this 
            clearInterval(that.Ttime);
            that.Ttime=setInterval(()=>{
                if(that.amampData.length > 0){
                    that.getEquipmentCodeData(that.amampData[Math.floor((Math.random()*that.amampData.length))])
                }
            },20000)
        },
        getNowTime() {
            this.nowTimer = setInterval(() => {
                this.nowTime = formatTimestamp(new Date(), 'yyyy-MM-dd hh:mm')
            }, 1000)
        }
    },
    beforeUnmount(){
        let that = this;
        clearInterval(that.Ttime)
        map.destroy();
    }
}
//高德标记点dom点击事件
window.onguanbi = function(event){
      map.remove(markerdd);
}
</script>

<style lang="scss" scoped>
// .video_ya {
//     position: absolute;
//     left: 320px;
//     top: -80px;
//     width: 1300px;
//     mix-blend-mode:lighten;
// //     mix-blend-mode
// //  background-blend-mode
// }
.dashboard {
    position: relative;
    height: 100%;
    color: white;
    .input-Calendar {
        position: absolute;
        left: 50%;
        top: 140px;
        transform: translate(-50%,-50%);
        width: 20%;
        z-index: 5;
        ::v-deep .el-input__inner {
            color: #fff;
            border : 0px solid #DCDFE6;
            height: 40px;
            background-color: rgba($color: #01415A, $alpha: 1.0);
        }
        ::v-deep .el-input--small .el-input__icon {
            line-height: 40px;
        }
    }
    .text-switch{
        position: absolute;
        display: flex;
        align-items: center;
        left: 520px;
        bottom: 30px;
        width: 200px;
        z-index: 5;
        .text-name {
            font-size: 16px;
            color: #5B8799;
            margin-left: 5px;
        }
    }
    .maptongy {
        position: absolute;
        left: 0;
        top: 0;
        height: 100%;
        width: 100%;
        z-index: 1;
    }
    .dashboard-header {
        position: relative;
        z-index: 5;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 113px;
        background: url("../../assets/img/dashboard/头部.png") no-repeat;
        background-size:100% 100%;
        background-position: 0px 10px;
        h1 {
            margin-top: -30px;
            font-family: FZHZ;
            text-align: center;
            letter-spacing:10px;
            font-size: 48px;
            color: #DADADA;
            background: linear-gradient(0deg, #00A8FF 0%, #38F8FF 100%);
            -webkit-text-fill-color: transparent;
            -webkit-background-clip: text;
        }
    }  
    .dashboard-box {
        height: calc(100% - 93px);
        position: relative;
        box-sizing: border-box;
        display: flex;
        margin-top: -20px;
        padding: 0px 20px;
        justify-content: space-between;
        .dashboard-left,.dashboard-right {
            display: flex;
            flex-flow: column;
            flex-shrink: 0;
            z-index: 5;
            >div {
                margin-bottom: 10px;
            }
        }
        .dashboard-left {
            width: 480px;
        }
        .dashboard-right {
            width: 410px;
        }
        .neirong-top {
            height: 280px;
            flex-shrink: 0;
        }
        .neirong-middle {
            flex: 1;
        }
        .neirong-bottom {
            height: 320px;
            flex-shrink: 0;
        }
    }
}
</style>